import csv
import time
from taobao_check.tools import PATH


class BlackList:
    env_ok = False
    first_read = True
    blacklist = []
    used = {}

    def __init__(self, print_log, no_log=False):
        self.print_log = print_log
        self.init_env(no_log)

    def init_env(self, debug):
        self.print_log(f"开始读取黑名单...", debug=debug)
        try:
            if BlackList.first_read:
                self.init_blacklist()
                self.init_used()
                BlackList.first_read = False
            self.env_ok = True
            self.print_log(f"黑名单读取成功！当前黑名单用户数为: {len(BlackList.blacklist)+len(BlackList.used)}", debug=debug)
        except Exception as e:
            self.print_log(f"黑名单读取失败，原因为: {e}", debug=debug)

    def init_blacklist(self):
        if not PATH.blacklist.is_file():
            with open(PATH.blacklist, "w", encoding="gbk", newline="") as f:
                writer = csv.writer(f)
                writer.writerow(["日期", "用户名"])

        with open(PATH.blacklist, "r", encoding="gbk", newline="") as f:
            reader = csv.reader(f)
            for row in reader:
                BlackList.blacklist.append(row[1])
        BlackList.blacklist = BlackList.blacklist[1:]

    def init_used(self):
        if not PATH.used.is_file():
            with open(PATH.used, "w", encoding="gbk", newline="") as f:
                writer = csv.writer(f)
                writer.writerow(["日期", "用户名", "店铺"])

        used = []
        with open(PATH.used, "r", encoding="gbk", newline="") as f:
            reader = csv.reader(f)
            for row in reader:
                used.append(row[1:])
        BlackList.used = dict(used[1:])

    def add_blacklist(self, username):
        if not PATH.blacklist.is_file():
            self.init_blacklist()
        BlackList.blacklist.append(username)
        now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        with open(PATH.blacklist, "a+", encoding="gbk", newline="") as f:
            writer = csv.writer(f)
            writer.writerow([now_time, username])

    def add_used(self, username, shop="无数据"):
        if not PATH.used.is_file():
            self.init_used()
        BlackList.used[username] = shop
        now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        with open(PATH.used, "a+", encoding="gbk", newline="") as f:
            writer = csv.writer(f)
            writer.writerow([now_time, username, shop])

    def check_user(self, username, shop="无数据"):
        if username in BlackList.blacklist:
            return False

        if username in BlackList.used:
            if BlackList.used[username] == shop:
                return False

        return True


if __name__ == "__main__":
    bl = BlackList()
    print("bl2")
    bl2 = BlackList()
    bl.add_blacklist("123")
    print(bl.blacklist, bl2.blacklist)
    bl2.add_blacklist("456")
    print(bl.blacklist, bl2.blacklist)
    # while True:
    #     user = input("输入用户名：")
    #     start = time.time()
    #     result = bl.check_user(user)
    #     print(f"time: {time.time() - start}")
    #     print(f"验号结果: {'通过' if result else '不通过'}")

